<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\index\util\Taoke;
use app\index\util\Page;
use think\Response;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = 'default';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        return $this->view->fetch();
    }

    public function test()
    {

        $tk = new Taoke;
        dump($tk->search_coupon('耳机'));
        return '';
    }

    protected function perform()
    {
        $keyword = input('get.keyword', '', 'urldecode');
        $p = input('get.page', 1, 'intval');
        $tmall = input('get.tmall', 'false');
        $oversea = input('get.overseas', 'false');
        $min_price = input('get.min_price');
        $max_price = input('get.max_price');
        $sort = input('get.sort');
        $model = model('UtaoSearch');
        $param = [
            'page_no' => $p,
        ];
        $tmall                 && $param['is_tmall'] = $tmall;
        $oversea               && $param['is_overseas'] = $oversea;
        $sort                  && $param['sort'] = $sort;
        is_numeric($min_price) && $param['start_price'] = $min_price;
        is_numeric($max_price) && $param['end_price'] = $max_price;
        $result = $model->search($keyword, $param);
        $page = Page::ready(20, $p, $result['total_results']);
        $ph = $page->render();
        $this->assign('query', json_encode(Page::get_query()));
        $this->assign('page', $ph);
        if (!$result) {
            $this->assign('list', []);
            $this->assign('error', $model->getError());
        } else {
            $this->assign('list', $result['result_list']['map_data']);
        }
    }

    public function search()
    {
        $this->perform();
        if ($this->request->isAjax()) {
            $this->view->engine->layout(false);
            return Response::create($this->fetch('index/good_list'), 'html');
        }
        return $this->fetch();
    }

    public function item()
    {
        $this->view->engine->layout(false);
        $item = json_decode(base64_decode(input('post.item')), true);
        if (!$item) $this->error('参数错误');
        $this->assign('item', $item);
        return Response::create($this->fetch(), 'html');
    }

}
